<template>
  <div>
    <px-form class="custom-form-ui visual-form" :model="queryParams" label-position="right" label-width="120px">
      <px-button type="primary" class="mr-[8px]" @click="getEqp">添加设备</px-button>
      <px-button type="primary" class="mr-[8px]" @click="seEqpByText">添加设备文本</px-button>
      <px-button type="danger" class="mr-[8px]" @click="delSelectEqp">删除所选设备</px-button>

      <px-button type="danger" class="mr-[8px]" @click="delAllEqp">清空设备</px-button>
      <px-button class="mr-[8px]" @click="updataPic">更新设备图片</px-button>
      <px-form-item label="过滤已经存在数据">
        <px-switch v-model="isFilter" size="small" />
      </px-form-item>
      <px-form-item label="设备名称">
        <px-input v-model="queryParams.eqpId" placeholder="请输入设备编号" clearable @keyup.enter="queryTable" />
      </px-form-item>
      <px-button type="primary" @click="queryTable">查询</px-button>
      <px-button @click="resetTable">重置</px-button>
    </px-form>
    <EqpTable
      v-model:queryParams="queryParams"
      :data="tableData"
      :eqpImgList="eqpImgList"
      :total="total"
      @queryTable="queryTable"
      @handleUploadPic="handleUploadPic"
      @handleDelete="handleDelete"
      @selection-change="handleSelectionChange"
      @handle-switch="handleSwitch"
      @handle-switch-liquid="handleSwitchLiquid"
      @handle-upload-cropper-delete="handleUploadCropperDelete"
    />
    <eqp-list v-model:visible="visible" :positionCode="null" @confirm="eqpListConfirm" />
    <HseEqpList v-model:visible="hseVisible" @confirm="eqpListConfirm" />
    <px-dialog v-model="eqpTextOpen" title="请粘贴文本" width="30%" align-center @close="eqpTextClose">
      <px-input v-model="eqpText" :rows="30" type="textarea" maxlength="999999" show-word-limit status="warning" placeholder="Please input" />
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="eqpTextClose">取消</px-button>
          <px-button type="primary" @click="eqpTextConfirm"> 确认 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import EqpTable from "./eqpTable.vue";
import EqpList from "./eqpList.vue";
import HseEqpList from "./hseEqpList.vue";

import {
  savePositionEqpRelation,
  listByPositionCode,
  delById,
  delTreeAllEqp,
  delTreeItemByIds,
  syncImg2TwinsConfig,
  delRealImgName,
  queryTemplData
} from "@/api/visual/visualConfig";
import { downloadPic } from "@visual/api/api";

const queryParams = ref({
  eqpId: ""
});

const visible = ref(false);
const tableData = ref([]);
const selectedTable = ref([]);
const eqpImgList = ref({});
const eqpTextOpen = ref(false);
const eqpText = ref("");
const total = ref(0);
const hseVisible = ref(false);
const isFilter = ref(false);
const props = defineProps({
  treeSelect: {
    type: Object || null
  },
  positionCode: {
    type: String || null
  },
  activeKey: {
    type: String || null
  },
  activeName: {
    type: String || null
  },
  eqpType: {
    type: String || null,
    default: "IFP"
  },
  imgUploadCut: {
    type: Number
  }
});

const emits = defineEmits(["handleUploadPic"]);
watch(
  () => [props.activeKey, props.treeSelect, props.imgUploadCut],
  val => {
    const [activeKey, treeSelect] = val;
    if (activeKey === props.activeName) {
      queryTable();
    }
  }
);
const getEqp = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  if (props.eqpType === "IFP") visible.value = true;
  else hseVisible.value = true;
};
const eqpListConfirm = async selectIds => {
  if (selectIds.length > 0) {
    let res = null;

    const saveData = selectIds.map(item => {
      return {
        positionCode: props.treeSelect.code,
        eqpId: item,
        eqpType: props.eqpType
      };
    });
    res = await savePositionEqpRelation(saveData);

    if (res) {
      PxMessage.success("添加设备成功");
      visible.value = false;
      hseVisible.value = false;
      queryTable();
    } else {
      PxMessage.warning("添加设备失败");
    }
  }
};
watch(isFilter, () => {
  queryTable();
});
// 查询设备列表
const queryTable = async () => {
  if (!props.treeSelect) return;
  const params = {
    positionCode: props.treeSelect.code,
    eqpType: props.eqpType,
    ...queryParams.value
  };
  if (!props.treeSelect) {
    return;
  }
  const data = (await listByPositionCode(params)) as any[];
  let drillComps = [];
  let routerKeys = [];
  let groupNames = [];
  if (isFilter.value) {
    const visualConfigRes = await queryTemplData({ twinsId: props.treeSelect.code, facCode: props.treeSelect.facCode });

    console.log(visualConfigRes);
    if (visualConfigRes?.json) {
      let json = JSON.parse(visualConfigRes?.json);
      json.forEach(item => {
        let pointStr = "DrillLocation TextLocation ColorLocation RectLocation VLocation DrillLocation2 MessageLocation";
        if (pointStr.includes(item.component)) {
          drillComps.push(item);
          if (item.propValue?.routerKey) {
            routerKeys.push(item.propValue?.routerKey);
          } else if (item.propValue?.code) {
            routerKeys.push(item.propValue?.code);
          }
          if (item.propValue?.groupName) {
            groupNames.push(item.propValue?.groupName);
          }
        } else if (item.component === "Group") {
          item?.propValue?.components?.forEach(item => {
            if (pointStr.includes(item.component)) {
              drillComps.push(item);
              if (item.propValue?.routerKey) {
                routerKeys.push(item.propValue?.routerKey);
              } else if (item.propValue?.code) {
                routerKeys.push(item.propValue?.code);
              }
              if (item.propValue?.groupName) {
                groupNames.push(item.propValue?.groupName);
              }
            }
          });
        }
      });
    }
  }
  if (isFilter.value) {
    tableData.value =
      data?.filter(item => {
        if (item.groupName) return !routerKeys.includes(item.eqpId) && !groupNames.includes(item.groupName);
        return !routerKeys.includes(item.eqpId);
      }) || [];
  } else {
    tableData.value = data || [];
  }
  selectedTable.value = [];
  for (let i = 0; i < data?.length; i++) {
    if (data[i].imgName) {
      await getImagByName(data[i].imgName);
    }
    if (data[i].realImgName) {
      await getImagByName(data[i].realImgName, true);
    }
  }
};
const getImagByName = async (name, isReal = false) => {
  if (!name) return;
  if (eqpImgList.value[name]) {
    return eqpImgList.value[name];
  }
  let data = { originalName: name, moduleName: "twins_visualization" };
  if (isReal) {
    data["moduleId"] = "9999";
  }
  let res = await downloadPic(data);
  if (res && res[0]) {
    const { fileUrl } = res[0];
    eqpImgList.value[name] = fileUrl;
    return fileUrl;
  }
  return "";
};
const seEqpByText = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  eqpTextOpen.value = true;
};
const eqpTextClose = () => {
  eqpTextOpen.value = false;
  eqpText.value = "";
};
const delSelectEqp = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  if (!selectedTable.value || selectedTable.value.length === 0) {
    PxMessage.warning("请选择要删除的数据节点");
    return;
  }
  const names = pluck(selectedTable.value, "eqpName");
  PxMessageBox.confirm('是否确认删除名称为"' + names.toString() + "的设备？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const ids = pluck(selectedTable.value, "id");
      const res = await delTreeItemByIds({ ids });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      await queryTable();
    })
    .catch(() => {});
};
const delAllEqp = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  const { code: positionCode, name } = props.treeSelect;
  PxMessageBox.confirm('是否确认删除名称为"' + name + "下的所有设备的数据项？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res = await delTreeAllEqp({ positionCode });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      await queryTable();
    })
    .catch(() => {});
};
const updataPic = () => {
  PxMessageBox.confirm("操作前请注意备份数据，操作后请及时验证", "风险提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      let params = { positionCode: props.positionCode, eqpIds: [] };
      if (selectedTable.value.length > 1) {
        params.eqpIds = pluck(selectedTable.value, "eqpId");
      }
      const res = await syncImg2TwinsConfig(params);
      PxMessage({
        message: "更新成功",
        type: "success"
      });
      queryTable();
    })
    .catch(() => {
      // PxMessage({
      //   message: "更新失败",
      //   type: "error"
      // });
    });
};
const handleDelete = async row => {
  PxMessageBox.confirm('是否确认删除设备属性id为"' + row.id + '"的数据项？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res = await delById(row.id);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    })
    .catch(() => {});
};
const handleUploadPic = row => {
  emits("handleUploadPic", row, props.eqpType);
};
const handleSelectionChange = datas => {
  selectedTable.value = datas;
};
const resetTable = () => {
  queryParams.value = {
    eqpId: ""
  };
  queryTable();
};
const eqpTextConfirm = async () => {
  if (!eqpText.value) {
    PxMessage.warning("请输入文本");
    return;
  }

  try {
    const saveData = eqpText.value.split("\n").map(item => {
      return {
        positionCode: props.treeSelect?.code,
        eqpId: item,
        eqpType: props.eqpType
      };
    });
    const res = await savePositionEqpRelation(saveData.filter(item => item.eqpId));
    if (res) {
      PxMessage.success("添加设备成功");
      queryTable();
      eqpTextClose();
    } else {
      PxMessage.warning("添加设备失败");
    }
  } catch (error) {
    console.error(error);
    PxMessage.warning("添加设备失败");
  }
};
function pluck(array, key) {
  return array.map(item => item[key]);
}
async function handleSwitch(row) {
  savePositionEqpRelationCom(row, "attr");
}
async function handleSwitchLiquid(row) {
  savePositionEqpRelationCom(row, "liquid");
}
async function savePositionEqpRelationCom(row, flag) {
  let { id, positionCode, eqpId, groupName, eqpType, showAttrInRoom, showLiquidLevelChange } = row;
  if (flag === "attr" && showAttrInRoom == 1) {
    showLiquidLevelChange = 0;
  } else if (flag === "liquid" && showLiquidLevelChange == 1) {
    showAttrInRoom = 0;
  }
  const res = await savePositionEqpRelation([
    { id, positionCode, eqpId, groupName, eqpType: eqpType ? eqpType : props.eqpType, showAttrInRoom, showLiquidLevelChange }
  ]);
  queryTable();
}
function handleUploadCropperDelete(row) {
  PxMessageBox.confirm("是否确认删除该图片？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      let res = await downloadPic({ originalName: row.realImgName, moduleName: "twins_visualization" });
      if (res && res[0]) {
        await delRealImgName({ eqpId: row.eqpId, fileId: res[0].id });
        PxMessage({
          message: "删除成功",
          type: "success"
        });
      } else {
        PxMessage.error("图片删除失败，请重试");
      }

      queryTable();
    })
    .catch(() => {
      PxMessage.error("图片删除失败，请重试");
    });
}
function configureObjectsByStringArray(stringArray, arrayObjects, key) {
  // 遍历数组对象
  return arrayObjects
    .map(item => {
      // 检查对象是否具有指定的键
      if (item.hasOwnProperty(key)) {
        // 检查字符串数组中是否有与对象键对应的值匹配的项
        if (stringArray.includes(item[key])) {
          // 如果匹配，保留该对象
          return item;
        }
      }
      // 如果不匹配，返回undefined（将被filter掉）
      return undefined;
    })
    .filter(item => item !== undefined); // 过滤掉undefined项
}
</script>
